package com.vitas.coin.data.room

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.snap.util.Util
import com.vitas.coin.data.bean.ChildrenVoiceBean

@Database(entities = [ChildrenVoiceBean::class], version = 7)
abstract class AppDatabase : RoomDatabase(){

    abstract fun collectDao(): CollectDao



    companion object {
        @Volatile
        private var INSTANCE: AppDatabase?= null
        fun getInstance(): AppDatabase =
            INSTANCE?: synchronized(this){
                INSTANCE?:buildDatabase(Util.getApp()).also {
                    INSTANCE = it
                }
            }

        /**
         * 版本升级3->4
         */
        private val MIGRATION_3_4 = object : Migration(3, 4) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE Test ADD COLUMN updatetime TEXT")
            }
        }

        private val MIGRATION_4_5 = object : Migration(4, 5) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE Test ADD COLUMN updatetime TEXT")
            }
        }


        private fun buildDatabase(context: Context) =
            Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "children_music.db")
                .fallbackToDestructiveMigration()
                .addMigrations(MIGRATION_3_4,MIGRATION_4_5)
                .build();
    }
}